package com.jgraves.WikiToSpeech;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;

import com.jgraves.WikiToSpeech.MakeSequence;

/** Extract script from Etherpad
 * @author johngraves
 *
 */
public class ReadEtherpad {

	public static void readEtherpad(final Context context, final InputStream instream, final Integer scriptSourceType) {
		if(null==instream){
			return;
		}
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(instream));

		try {
			String line;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
				Integer initialAttributedTextAt = line.indexOf("\"initialAttributedText\":{\"text\"");
				if (0<initialAttributedTextAt) {
//					print("Found Etherpad markings");
					String scriptString = line.substring(initialAttributedTextAt+33,line.indexOf("\",\"attribs\":", initialAttributedTextAt));
					String[] preStringArray = scriptString.split("\\\\n");
					State.setSequence(MakeSequence.makeSequence(context, preStringArray, false));
					State.clearQuestionsVisited();
					State.setOnQuestion(0);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
